package com.chebaohui.iqs.service.impl;

import java.security.MessageDigest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import org.springframework.stereotype.Service;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.chebaohui.iqs.config.MessageCode;
import com.chebaohui.iqs.config.ResultCode;
import com.chebaohui.iqs.entity.Paramter;
import com.chebaohui.iqs.entity.Result;
import com.chebaohui.iqs.entity.base.Message;
import com.chebaohui.iqs.service.MessageService;
import com.chebaohui.iqs.service.impl.deal.util.StringUtil;

/**
 * @author regas_xie
 *
 */
@Service
public class MessageServiceImpl implements MessageService {
	/**
	 * log:日志输出
	 */
	private static Log log = LogFactory.getLog(MessageServiceImpl.class);

	@Override
	public Result<Object> send(Paramter<Message> param) {
		MessageCode req = null;
		try {
			// 电话号码判断
			if (!StringUtil.valFormat(param.getData().getPhone(),
					"^(17[0-9]|13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$"))
				return new Result<>(ResultCode.L02, "电话号码格式错误:" + param.getData().getPhone());

			if (StringUtil.isNulls(param.getData().getMsg()))
				return new Result<>(ResultCode.L02, "短信内容格式错误:" + param.getData().getMsg());
			// 验证短信类型
			for (MessageCode msg : MessageCode.values()) {
				if (msg.getCode().equals(param.getData().getType())) {
					req = msg;
					break;
				}
			}

			if (null == req)
				return new Result<>(ResultCode.L02, "短信类型错误:" + param.getData().getType());
			if (StringUtil.isNulls(req.getMsgValue()))
				return new Result<>(ResultCode.N02, "短信模版未配置:" + req.getValue());

			Object t = new Object();
			String content = req.getMsgValue();//短信模版详细获取

			String[] lists=param.getData().getMsg().split("##");//变量值集合
			for(int i=0;i<lists.length;i++){
				content = content.replace("【变量"+i+"】", lists[i]);
			}

			t = content;
			String res = sendMessage(param.getData().getPhone(), content);

			if ("true".equals(res)) {
				return new Result<>(ResultCode.SUCCESS, t);
			} else {
				Result<Object> result = new Result<>(ResultCode.N02, "短信发送失败:" + res);
				result.setData(t);
				return result;
			}
		} catch (Exception e) {
			return new Result<>(ResultCode.N02, "短信发送异常:" + e.getMessage());
		}

	}

	private static String account = "cf_upincc";
	private static String password = "UPINCC@2014";
	/* 发送短信验证码 */
	private static String submit = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

	/**
	 * 短信发送
	 * 
	 * @param phone
	 *            手机号
	 * @param content
	 *            短信内容
	 * @return
	 */
	public static String sendMessage(String phone, String content) {
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(submit);
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
		NameValuePair[] data = { // 提交短信
				new NameValuePair("account", account), new NameValuePair("password", MD5Encode(password)),
				new NameValuePair("mobile", phone), new NameValuePair("content", content), };
		method.setRequestBody(data);

		try {
			client.executeMethod(method);
			String SubmitResult = method.getResponseBodyAsString();
			log.info("短信" + phone + "发送返回:" + SubmitResult);
			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();
			String code = root.elementText("code");
			String msg = root.elementText("msg");
			// String smsid = root.elementText("smsid");
			if ("2".equals(code)) {
				return "true";
			} else
				return msg;
		} catch (Exception e) {
			return "短信发送异常:" + e.getMessage();
		} finally {
			method.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}
	}

	/**
	 * 加密
	 * 
	 * @param origin
	 * @return
	 */
	public static String MD5Encode(String origin) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
		}
		return resultString;
	}

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b
	 *            字节数组
	 * @return 16进制字串
	 */
	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };
}
